import {
  login,
  logout
} from '@/api/src/public'
import {
  getToken,
  getUserInfo,
  setUserInfo,
  removeUserInfo
} from '@/utils/auth'

const userInfo = getUserInfo()

const state = {
  token: getToken(),
  userInfo: userInfo,
  isSuperAdmin: ''
}

const getters = {
  token: state => state.token,
  userInfo: state => state.userInfo,
  isSuperAdmin: state => state.isSuperAdmin
}

// 同步
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },

  SET_USER_INFO: (state, info) => {
    state.userInfo = info
  },

  IS_SUPER_ADMIN: (state, isSuperAdmin) => {
    state.isSuperAdmin = isSuperAdmin
  }
}

// 异步
const actions = {
  Login ({ commit }, data) {
    return new Promise((resolve, reject) => {
      login(data).then(data => {
        if (data) {
          removeUserInfo()
          let { user } = data
          commit('SET_USER_INFO', user)
          // 判断是否为超级管理员 Boolean
          commit('IS_SUPER_ADMIN', user.pris === '10000')
          user.accessToken ? commit('SET_TOKEN', user.accessToken) : commit('SET_TOKEN', '')
          setUserInfo(user)
        }
        resolve(data)
      }).catch(err => {
        reject(err)
      })
    })
  },

  Logout () {
    return new Promise((resolve, reject) => {
      logout().then(res => {
        removeUserInfo()
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
